<template>
  <el-dialog
    :title="title"
    :visible.sync="visible"
    width="825px"
    :before-close="handleClose">
    <el-form ref="form" class="form" :rules="rules" :model="form" label-width="80px" label-position="top">
      <el-form-item label="设备类型" prop="deviceType">
        <el-select v-model="form.deviceType" :disabled="type!=='add'" placeholder="请选择">
          <el-option v-for="item in deviceTypeList" :label="item.attributeName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="deviceCode" label="设备编码">
        <el-input :disabled="type!=='add'" v-model="form.deviceCode"></el-input>
      </el-form-item>
      <el-form-item prop="deviceName" label="设备名称">
        <el-input :disabled="type === 'view'" v-model="form.deviceName"></el-input>
      </el-form-item>
<!--      <el-form-item prop="electricityId"-->
<!--                    v-if="deviceType==='experiment_sensor'"-->
<!--                    label="关联电表">-->
<!--        <el-select :disabled="type === 'view'" v-model="form.electricityId" placeholder="请选择">-->
<!--          <el-option v-for="item in electricityList" :label="item.deviceName" :value="item.id"></el-option>-->
<!--        </el-select>-->
<!--      </el-form-item>-->
<!--      <el-form-item prop="avoltage" label="关联电压项"-->
<!--                    v-if="deviceType==='experiment_sensor'">-->
<!--        <el-select :disabled="type === 'view'" v-model="form.avoltage" placeholder="请选择">-->
<!--          <el-option v-for="item in avoltageList" :label="item.name" :value="item.value"></el-option>-->
<!--        </el-select>-->
<!--      </el-form-item>-->
      <el-form-item prop="ipAddress"
                    v-if="deviceType==='HAIKANG_CAMERA'"
                    label="摄像头IP">
        <el-input :disabled="type === 'view'" v-model="form.ipAddress"></el-input>
      </el-form-item>
      <el-form-item prop="portValue"
                    v-if="deviceType==='HAIKANG_CAMERA'"
                    label="端口号">
        <el-input v-model="form.portValue"></el-input>
      </el-form-item>
      <el-form-item prop="mqttUserName"
                    v-if="deviceType==='HAIKANG_CAMERA'"
                    label="账号">
        <el-input :disabled="type === 'view'" v-model="form.mqttUserName"></el-input>
      </el-form-item>
      <el-form-item prop="mqttPwd"
                    v-if="deviceType==='HAIKANG_CAMERA'"
                    label="密码">
        <el-input :disabled="type === 'view'" v-model="form.mqttPwd" type="password"></el-input>
      </el-form-item>
      <el-form-item prop="deptId"  label="机构">
        <el-cascader
          class="w-100"
          :disabled="type === 'view'"
          :options="orgTree"
          v-model="form.deptId"
          :props="options"
          :show-all-levels="false"
        ></el-cascader>
      </el-form-item>
      <el-form-item label="备注">
        <el-input :disabled="type === 'view'" v-model="form.remark"></el-input>
      </el-form-item>
      <el-form-item prop="isSecurity"  v-if="deviceType==='HAIKANG_CAMERA'" label="电子围栏">
        <el-switch
          :disabled="type === 'view'"
          v-model="form.isSecurity"
         >
        </el-switch>
      </el-form-item>
      <el-form-item prop="isThermal"  v-if="deviceType==='HAIKANG_CAMERA'" label="是否支持红外">
        <el-switch
          :disabled="type === 'view'"
          v-model="form.isThermal"
        >
        </el-switch>
      </el-form-item>
      <el-form-item prop="isTurn"  v-if="deviceType==='HAIKANG_CAMERA'" label="是否支持巡检转动">
        <el-switch
          :disabled="type === 'view'"
          v-model="form.isTurn"
        >
        </el-switch>
      </el-form-item>

    </el-form>
    <!--实时值-->
    <div class="detail-data"
         v-if="type === 'view' && deviceType!=='HAIKANG_CAMERA'">
      <div class="item flex-box pointer" @click="itemClick(item)" v-for="item in detailList">
        <img :src="require(`../../../assets/img/device/${codeImg(item.attributeCode)}.png`)" alt="">
        <div class="flex-column">
          <div class="value flex-end">
            <span>{{item.attributeValue}}</span>
            <span class="unit">{{item.attributeCode|unit}}</span>
          </div>
          <span>{{item.attributeName}}</span>
        </div>
      </div>
      <div class="item flex-box">
        <img
          :src="form.status===1?require('../../../assets/img/device/normal.png'):require('../../../assets/img/device/error.png')"
          alt="">
        <div class="flex-column">
          <span class="value">{{form.status|status}}</span>
          <span>状态</span>
        </div>
      </div>
    </div>
    <!--摄像头-->
    <div class="video-data flex-start"
         v-if="type === 'view' && deviceType==='HAIKANG_CAMERA'">
      <video controls id="flv-video" class="flv-video" ></video>
      <div class="item flex-box">
        <img
          :src="form.status===1?require('../../../assets/img/device/normal.png'):require('../../../assets/img/device/error.png')"
          alt="">
        <div class="flex-column">
          <span class="value">{{form.status|status}}</span>
          <span>状态</span>
        </div>
      </div>
    </div>
    <span slot="footer" v-if="['add','edit'].includes(type)" class="dialog-footer">
    <el-button @click="handleClose">取 消</el-button>
    <el-button type="primary" @click="handleConfirm">确 定</el-button>
  </span>
    <!--图表弹窗-->
    <charts-modal ref="chartsModal" :deviceType="chartType" :deviceIds="form.id">
      <div class="detail-data" v-if="['water_meter','environ_sensor'].includes(deviceType)">
        <div class="item flex-box pointer" @click="itemClick(item)" v-for="item in detailList.filter(o=>{return o.attributeCode === chartType})">
          <img :src="require(`../../../assets/img/device/${codeImg(item.attributeCode)}.png`)" alt="">
          <div class="flex-column">
            <div class="value flex-end">
              <span>{{item.attributeValue}}</span>
              <span class="unit">{{item.attributeCode|unit}}</span>
            </div>
            <span>{{item.attributeName}}</span>
          </div>
        </div>
      </div>
    </charts-modal>
  </el-dialog>
</template>
<script>
  import {getAssociatedDb, add, update, getDetail,getHistory} from "../../../api/platform/devicetable";
  import {pullStream} from "../../../api/camera";
  import chartsModal from './charts-modal'
  import flvjs from 'flv.js'
  import {findName,deepFind} from "../../../util/util";
  import {getDeptTree} from "../../../api/system/dept";

  export default {
    name: 'add-device',
    props: {
      deviceTypeList: {
        type: Array,
        default: () => []
      }
    },
    components:{
      chartsModal
    },
    data() {
      return {
        visible: false,
        type: 'add',
        // avoltageList: [
        //   {
        //     name: 'A项',
        //     value: 'A'
        //   }, {
        //     name: 'B项',
        //     value: 'B'
        //   }, {
        //     name: 'C项',
        //     value: 'C'
        //   },
        // ],
        // electricityList: [],
        form: {},
        detailList: [],
        player:null,
        chartType:'',
        orgTree:[],
        options:{
          value:'id',
          label:'title'
        }
      }
    },
    computed: {
      title() {
        switch (this.type) {
          case "add":
            return '新增';
          case 'edit':
            return '编辑';
          case 'view':
            return '查看'
        }
      },
      deviceType(){
        return findName(this.form.deviceType, this.deviceTypeList, 'id', 'attributeCode')
      },
      rules() {
        let rules = {
          deviceType: [{required: true, message: '请选择设备类型'}],
          deviceName: [{required: true, message: '请输入设备名称'}],
          deviceCode: [{required: true, message: '请输入设备编码'}],
          deptId:[{required: true, message: '请选择机构'}],
        }
        if (this.deviceType === 'experiment_sensor') {
          rules.avoltage = [{required: true, message: '请选择关联电压项'}]
          rules.electricityId = [{required: true, message: '请选择关联电表'}]
        }
        if (this.deviceType === 'HAIKANG_CAMERA') {
          rules.ipAddress = [{required: true, message: '请输入摄像头IP'}]
          rules.portValue = [{required: true, message: '请输入端口号'}]
          rules.mqttUserName = [{required: true, message: '请输入账号'}]
          rules.mqttPwd = [{required: true, message: '请输入密码'}]
        }
        return rules
      }
    },
    methods: {
      destoryFlv(){
        if(this.player){
          this.player.pause();
          this.player.unload();
          this.player.detachMediaElement();
          this.player.destroy();
          this.player=null
        }
      },
      initFlv(url){
        if (flvjs.isSupported()) {
          var videoElement = document.getElementById('flv-video');
          this.player = flvjs.createPlayer({
            type: 'flv',
            isLive: false,
            hasAudio: false,
            url		// 自己的flv视频流
          });
          this.player.attachMediaElement(videoElement);
          this.player.load();
          this.player.play();
        }
      },
      itemClick(item){
        this.chartType = item.attributeCode
        this.$refs.chartsModal.showModal()
      },
      /*获取电表下拉框*/
      getDb() {
        getAssociatedDb().then(res => {
          this.electricityList = res.data.data;
        })
      },
      detail() {
        getDetail(this.form.id).then(res => {
          const dispalyKeyArr = ["humidity","temperature","pressure","powerRead","acurrent","bcurrent","ccurrent","avoltage","bvoltage","cvoltage"]
          this.detailList = res.data.data.filter(o=>{
            return dispalyKeyArr.includes(o.attributeCode)
          })
          console.log(this.deviceType);
          if(this.deviceType !== 'experiment_sensor'){
            this.detailList = this.detailList.concat([{
              attributeCode:"currentHarmonic",
              attributeName:"电流谐波",
            },{
              attributeCode:"voltageHarmonic",
              attributeName:"电压谐波",
            }])
          }

        })
      },
      showModal() {
        this.visible = true;
        if (this.type === 'view' && this.deviceType !== 'HAIKANG_CAMERA') {
          this.detail()
        }
        // if(this.deviceType === 'experiment_sensor'){
        //   this.getDb()
        // }
        if(this.type === 'view' && this.deviceType === 'HAIKANG_CAMERA' ){
          this.pullStream()
        }
        getDeptTree().then(res=>{
          console.log(res);
          this.orgTree = res.data.data;
        })
      },
      pullStream(){
        pullStream(this.form.id).then(res=>{
          console.log(res);
          this.initFlv(res.data.data.flvUrl)
        })
      },
      handleClose() {
        this.form = {}
        this.detailList = [];
        this.visible = false
        this.$refs.form.resetFields()
      },
      codeImg(val) {
        switch (val) {
          case 'powerRead':
          case 'acurrent':
          case 'bcurrent':
          case 'ccurrent':
          case 'acurrentHarmonic':
          case 'bcurrentHarmonic':
          case 'ccurrentHarmonic':
          case 'currentHarmonic':
            return 'dianliu';
          case 'avoltage':
          case 'bvoltage':
          case 'cvoltage':
          case 'avoltageHarmonic':
          case 'bvoltageHarmonic':
          case 'cvoltageHarmonic':
          case 'voltageHarmonic':
            return 'dianya'
          default:
            return val
        }
      },
      handleConfirm() {
        this.$refs.form.validate(valid => {
          if (valid) {
            let data = _.cloneDeep(this.form);
            // data.deptId = this.form.deptId[this.form.deptId.length-1];
            data.deptName = deepFind(this.orgTree,o=>{
              return o.id === data.deptId[data.deptId.length-1]
            }).title
            data.deptId = data.deptId.toString()
            if(this.deviceType === 'HAIKANG_CAMERA'){
              if(!data.hasOwnProperty('isSecurity')) data.isSecurity = false
              if(!data.hasOwnProperty('isThermal')) data.isThermal = false
              if(!data.hasOwnProperty('isTurn')) data.isTurn = false
            }
            if (this.type === 'add') {
              add(data).then(res => {
                this.$message.success('新增成功!');
                this.$emit('success')
                this.handleClose()
              })
            }
            if (this.type === 'edit') {
              update(data).then(res => {
                this.$message.success('修改成功!');
                this.$emit('success')
                this.handleClose()
              })
            }

          }
        })

      }
    },
    filters: {

      unit(val) {
        switch (val) {
          case "humidity":
            return '%'
          case "pressure":
            return 'Pa'
          case "temperature":
            return '℃'
          case "flowCount":
            return 't'
        }
      },
      status(val) {
        switch (val) {
          case 1:
            return '正常'
          case 2:
            return '异常'
        }
      },
    }
  }
</script>
<style scoped lang="scss">
  .form {
    display: grid;
    grid-column-gap: 20px;

    grid-template-columns: repeat(3, 1fr);

    .el-select {
      width: 100%;
    }
  }
  .video-data{
    .flv-video{
      width: 244px;
      height: 166px;
      margin-right: 30px;
    }
    .item {
      border: 1px dashed #1068FF;
      border-radius: 8px;
      background: rgba(16, 104, 255, 0.04);
      color: #5A6E90;
      padding: 12px 10px;
      width: 152px;
      img{
        margin-right: 5px;
      }
      .value {
        font-size: 20px;
        color: #0C2550;

        .unit {
          font-size: 12px;
          margin-left: 3px;
          color: #5A6E90;
        }
      }
    }
  }
  .detail-data {
    display: grid;
    grid-gap: 20px;
    grid-template-columns: repeat(4, 1fr);

    .item {
      border: 1px dashed #1068FF;
      border-radius: 8px;
      background: rgba(16, 104, 255, 0.04);
      color: #5A6E90;
      padding: 12px 10px;
      img{
        margin-right: 5px;
      }
      .value {
        font-size: 20px;
        color: #0C2550;

        .unit {
          font-size: 12px;
          margin-left: 3px;
          color: #5A6E90;
        }
      }
    }
  }
</style>
